﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.IO;
using System.Configuration;

public class PhotoManager
{
    private static readonly string _thumbFolder = ConfigurationManager.AppSettings["folderForThumbnails"];
    private static readonly string _albumFolder = ConfigurationManager.AppSettings["folderForImages"];
    private int _albumId;

    public PhotoManager(int albumId)
    {
        _albumId = albumId;
    }

    public List<string> GetUrlsOfAllPhotos(string baseAlbumsFolder)
    {
        string fullpath = baseAlbumsFolder + _thumbFolder;
        DirectoryInfo dir = new DirectoryInfo(fullpath);
        FileInfo[] bitmapFiles = dir.GetFiles("*.*");
        List<string> files = new List<string>();
        foreach (FileInfo f in bitmapFiles)
        {
            string fileExtension = Path.GetExtension(f.Name).ToLower();
            if (ConfigurationManager.AppSettings["allowedExtensions"].Split(',').ToArray().Contains(fileExtension))
                files.AddRange(System.IO.Directory.GetFiles(fullpath, f.Name));
        }
        return files;
    }

    public void DeleteAlbumPhotos(string folderPath)
    {
        try
        {
            Directory.Delete(folderPath, true);
        }
        catch
        {
 
        }
    }

    public int GetPhotosNumber(string folderPath)
    {
        return Directory.GetFiles(folderPath).Length;
    }

    public bool DeleteImages(List<string> urls)
    {
      foreach(string url in urls)
      {
          string imgDelPath = url.Replace("\\Thumbnails", string.Empty);
          try
          {
              File.Delete(imgDelPath);
              File.Delete(url);
          }
          catch
          {
              return false;
          }
      }
      
        return true;      
    }
    public string GetRelativePath(string url)
    {
        string apppath = url.Substring(0, url.IndexOf(_albumFolder));
        return url.Replace(apppath, "~/");
    }

    public string GetFullUrlFromThumbNail(string url)
    {
        string result = "";
        string[] splitUrl = url.Split('/');
        for (int i = 0; i < splitUrl.Count() - 2; i++)
        {
            result += splitUrl[i] + "/";
        }
        result += splitUrl[splitUrl.Count() - 1];
        return result;
    }

    public static void CreateAlbumFolder(string baseAlbumsFolder, int albumId)
    {
        string DestinationPathForAlbum = Path.Combine(baseAlbumsFolder, albumId.ToString());
        string DestinationPathForThumbnails = DestinationPathForAlbum + ConfigurationManager.AppSettings["folderForThumbnails"];
        Directory.CreateDirectory(DestinationPathForAlbum);
        Directory.CreateDirectory(DestinationPathForThumbnails);
    }
}